package com.example.luozizhao.eprxdemo.utils;

import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.Key;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * @author qiwenming
 * @date 2015-10-29 下午5:36:11
 * @ClassName EncodeUtil
 * @Package com.cshtong.app.utils
 * @Description: 编码相关工具类
 */
public class EncodeUtil {
	/**
	 * MD5加密
	 * 
	 * @param s
	 * @return
	 */
	/*
	 * public final static String encode_MD5(String s) { char
	 * hexDigits[]={'0','1'
	 * ,'2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; try { byte[]
	 * btInput = s.getBytes(); // 获得MD5摘要算法的 MessageDigest 对象 MessageDigest
	 * mdInst = MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要
	 * mdInst.update(btInput); // 获得密文 byte[] md = mdInst.digest(); //
	 * 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k =
	 * 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] =
	 * hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return
	 * new String(str); } catch (Exception e) { e.printStackTrace(); return "";
	 * } }
	 */

	public static String encode_MD5(String sSecret) {
		try {
			MessageDigest bmd5 = MessageDigest.getInstance("MD5");
			bmd5.update(sSecret.getBytes());
			int i;
			StringBuffer buf = new StringBuffer();
			byte[] b = bmd5.digest();
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static byte[] encryptDecryptByPublicKey(byte[] data, String key,
			int mode) throws Exception {
		// 对钥解密
		byte[] keyBytes = decryptBASE64(key);

		// 取钥
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		Key publicKey = keyFactory.generatePublic(x509KeySpec);

		// 加密解密
//		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		cipher.init(mode, publicKey);

		return cipher.doFinal(data);
	}

	public static byte[] decryptBASE64(String key) throws Exception {
//		byte[] temp = Base64Utils.decodeFromString(key);
		return Base64.decode(key, Base64.NO_WRAP);
	}
	
	/**
	 * @param publicKey 公钥
	 * @param password 密码
	 * @return 加密后的密文
	 * @throws Exception
	 */
	public static String getPublicKey(String publicKey, String password) throws Exception {
		byte[] data = password.getBytes();
		byte[] encodedData = encryptDecryptByPublicKey(data, publicKey, Cipher.ENCRYPT_MODE);
//		String temp = Base64Utils.encodeToString(encodedData);
		return Base64.encodeToString(encodedData, Base64.NO_WRAP);
	}

	private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
	public static String encodeToString(byte[] src) {
		if (src == null) {
			return null;
		}
		if (src.length == 0) {
			return "";
		}
		return new String(Base64.encode(src, Base64.DEFAULT), DEFAULT_CHARSET);
	}

	public static byte[] decodeFromString(String src) {
		if (src == null) {
			return null;
		}
		if (src.length() == 0) {
			return new byte[0];
		}
		return Base64.decode(src.getBytes(DEFAULT_CHARSET), Base64.DEFAULT);
	}
	
    public static String encodeChineseURLParameter(String param) {
        String result = null;
        try {
            result = URLEncoder.encode(param, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            result = param;
            e.printStackTrace();
        }
        return result;
    }
}